<script setup lang="ts">
import { ref } from 'vue';
import { getCity, getCityList } from '@/api/index'
import { useCounterStore } from '@/stores/counter';
import { storeToRefs } from 'pinia';
import { useRouter } from 'vue-router';

const router = useRouter()

// 在pinia 获取城市ID
const counterStore = useCounterStore();
const { cityId, cityName, latitude, longitude } = storeToRefs(counterStore);

// const latitude = ref(null);
// const longitude = ref(null);

// 获取经纬度
const getLocation = () => {

    if ("geolocation" in navigator) {
        navigator.geolocation.getCurrentPosition(
            (position) => {
                latitude.value = position.coords.latitude;
                longitude.value = position.coords.longitude;

                getCity(latitude.value, longitude.value).then(res => {
                    console.log(res.data.data);
                    cityId.value = res.data.data.id
                    cityName.value = res.data.data.city
                    // router.replace('/')
                })
            },
            (error) => {
                switch (error.code) {
                    case error.PERMISSION_DENIED:
                        console.error("用户拒绝了地理位置请求。");
                        break;
                    case error.POSITION_UNAVAILABLE:
                        console.error("位置信息不可用。");
                        break;
                    case error.TIMEOUT:
                        console.error("请求用户位置超时。");
                        break;
                    case error.UNKNOWN_ERROR:
                        console.error("未知错误发生了。");
                        break;
                }
            }
        );
    } else {
        console.log("您的浏览器不支持地理位置API。");
    }
};

// 获取城市列表
const cityList = ref([])
const hotCityList = ref([])

const result = ref([])
getCityList().then(res => {
    console.log(res.data);
    result.value = res.data.cts.sort((a, b) => {
        if (a.py > b.py) {
            return 1
        } else if (a.py < b.py) {
            return -1
        } else {
            return 0
        }
    })
    // 所有城市,按照首字母排序
    for (const item of result.value) {
        // 将第一个字母转成大写
        const firstLetter = item.py[0].toUpperCase();

        // 判断第一个字母是否存在
        if (!cityList.value.some(group => group[0] === firstLetter)) {
            // 不存在将数据存入二维数组
            cityList.value.push([firstLetter, [item]]);
        } else {
            // 存在查找对应数组的index，并保存item
            const index = cityList.value.findIndex(group => group[0] === firstLetter);
            cityList.value[index][1].push(item);
        }
    }

    // 热门城市
    hotCityList.value = res.data.hot
})

// 热门城市经纬度
const handleCity = (c: string) => {
    let city = result.value.filter(item => {
        return item.nm === c
    })
    console.log(city);

    cityId.value = city[0].id
    cityName.value = c
    router.replace('/')
}
</script>
<template>
    <header>
        <header>
            <div class="back" @click="$router.back()"><van-icon name="arrow-left" size="20rem" color="#000" /></div>
            <div class="title" v-if="cityName">当前位置 - {{ cityName }}</div>
            <div class="title" v-else>请打开定位</div>
        </header>
        <van-search placeholder="请输入搜索关键词" />
        <div class="mylocal">
            <p class="top">定位城市</p>
            <div class="btn" v-if="!cityName" @click="getLocation"><van-icon name="location-o" size="18"
                    color="#e54847" />获取我的位置</div>
            <div class="btn" v-else><van-icon name="location-o" size="18" color="#e54847" /> {{ cityName }}</div>
        </div>
        <div class="mylocal">
            <p class="top">热门城市</p>
            <ul class="hot">
                <li v-for="city in hotCityList" @click="handleCity(city)">
                    {{ city }}
                </li>
            </ul>
        </div>

        <!-- 索引栏 -->
        <van-index-bar v-for="(group, index) in cityList" :key="index" highlight-color="#e54847">
            <van-index-anchor :index="group[0]" />
            <van-cell v-for="item in group[1]" :key="item.id" :title="item.nm"
                @click="cityId = item.id; cityName = item.nm; $router.replace('/')" />
        </van-index-bar>

    </header>
</template>
<style lang="less" scoped>
header {
    background-color: #fff;
    border-bottom: 1px solid #00000018;
    position: relative;

    .back {
        position: absolute;
        left: 10rem;
        top: 12rem;
    }

    .title {
        font-size: 14rem;
        text-align: center;
        height: rem;
        padding: .12rem;
        color: #000;
        height: 50rem;
        display: flex;
        align-items: center;
        justify-content: space-around;
    }

}

.mylocal {
    padding: 12rem;
    width: 86%;

    .top {
        font-size: 14rem;
        text-align: center;
        text-align: left;
        margin-top: 0;
    }

    .btn {
        border: 1px solid #ccc;
        padding: 8rem;
        width: 104rem;
        border-radius: 4rem;
        font-size: 14rem;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .hot {
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        li {
            font-size: 14rem;
            width: 25%;
            margin: 8rem 4rem;
            border: 1px solid #ccc;
            border-radius: 4rem;
            padding: 8rem;
            text-align: center;
        }
    }

    .allCity {
        li {
            padding: 12rem 6rem;
            font-size: 14rem;
            border-bottom: 1px solid #cccccc61;
        }
    }
}

:deep(.van-index-bar__index) {
    font-size: 12rem;
    font-weight: lighter;
    color: #5e5e5e;
    margin-bottom: 2rem;
}
</style>